package com.service;
import static com.def.GenericDef.ACTION_FLG_ADD;
import static com.def.GenericDef.ACTION_FLG_CANCEL;
import static com.def.GenericDef.ACTION_FLG_DELETE;
import static com.def.GenericDef.ACTION_FLG_INQUIRE;
import static com.def.GenericDef.ACTION_FLG_NEW;
import static com.def.GenericDef.ACTION_FLG_QUERY;
import static com.def.GenericDef.ACTION_FLG_REPLACE;
import static com.def.GenericDef.ACTION_FLG_UPDATE;
import static com.def.GenericDef.RETURN_CODE_OK;
import static com.def.GenericDef.RETURN_CODE_SET_ERROR;
import static com.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.def.GenericDef.RETURN_MESG_OK;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dao.IBisDataDao;
import com.icim.service.ICIMBaseService;
import com.model.Bis_data;
import com.tx.Xplstdat.XplstdatI;
import com.tx.Xplstdat.XplstdatIA;
import com.tx.Xplstdat.XplstdatO;
import com.tx.Xplstdat.XplstdatOA;
import com.util.GUIDGenerator;
import com.util.MqOpe;

@Scope("prototype")
@Service("XplstdatService")
public class XplstdatService extends ICIMBaseService{
	
	private Logger logger = Logger.getLogger(XplstdatService.class);
	@Autowired
	private XplstdatI xplstdatI;
	
	@Autowired
	private XplstdatO xplstdatO; 
	
	
	@Autowired
	private IBisDataDao bisDataDao;
	
	@Autowired
	private MqOpe mqOpe;
	
	public String subMainProc(String strInMsg){
		logger.info("InTrx is "+ strInMsg );
//		AppContext.clear();
//		AppContext.setCurrServiceName(this.getClass().getSimpleName());
		Session session = bisDataDao.getCrSession();
		try{
			xplstdatI = (XplstdatI) mqOpe.inStr2Obj(strInMsg,xplstdatI);
			xplstdatO.setTrx_id("XPLSTDAT");
			xplstdatO.setType_id("O");
			char action_flg = xplstdatI.getAction_flg().charAt(0);
			switch(action_flg){
				case ACTION_FLG_QUERY   : xplstdatO = queryByCondition()  ; break;
				case ACTION_FLG_ADD     : xplstdatO = addFnc()            ; break;
				case ACTION_FLG_UPDATE  : xplstdatO = updateFnc()         ; break;
				case ACTION_FLG_DELETE  : xplstdatO = deleteFnc()         ; break;
				case ACTION_FLG_NEW     : xplstdatO = addDataCateProc()   ; break;
				case ACTION_FLG_REPLACE : xplstdatO = updateDataCateProc(); break;
				case ACTION_FLG_CANCEL  : xplstdatO = deleteDataCateProc(); break;
				case ACTION_FLG_INQUIRE : xplstdatO = queryByExt()        ; break;
				case 'T'                : xplstdatO = deleteByDataCateExt1(); break;
				case 'W'                : xplstdatO = addByDataCateExt1(); break;
				case 'S'                : xplstdatO = queryDataByCateUser(); break;
				case 'O'                : xplstdatO = listDataBySort(); break;
				case 'B'                : xplstdatO = queryByExt5(); break;
				case 'F'                : xplstdatO = queryDataByFabUser(); break;
				case 'E'                : xplstdatO = queryByConditioncs()  ; break;
				case 'G'                : xplstdatO = queryformaker();break;
				case 'H'                : xplstdatO = querybycate();break;
				default                 : xplstdatO = errActionFnc();   
			}
		    if( RETURN_CODE_OK.equals(xplstdatO.getRtn_code()) ){
		    	session.flush();
			}else{
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}		
		}catch(Exception ex){
			xplstdatO.setTrx_id("XPLSTDAT");
			xplstdatO.setType_id("O");
			xplstdatO.setRtn_code(RETURN_CODE_UNKNOWN);
			xplstdatO.setRtn_mesg(ex.getCause().toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}finally{
			logger.info(mqOpe.obj2Str(xplstdatO));
			return mqOpe.obj2Str(xplstdatO);
		}
		
	}
	public XplstdatO addFnc(){
		XplstdatO  xplstdatO = bisDataDao.addProc(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO updateFnc(){
		XplstdatO  xplstdatO = bisDataDao.updateProc(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO deleteFnc(){
		XplstdatO  xplstdatO = bisDataDao.deleteProc(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO queryByCondition(){
		XplstdatO  xplstdatO = bisDataDao.queryByCondition(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO queryByConditioncs(){
		XplstdatO  xplstdatO = bisDataDao.queryByConditioncs(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO queryformaker(){
		XplstdatO  xplstdatO = bisDataDao.queryformaker(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO addDataCateProc(){
		XplstdatO  xplstdatO = bisDataDao.addDataCateProc(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO updateDataCateProc(){
		XplstdatO xplstdatO = bisDataDao.updateDataCateProc(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO deleteDataCateProc(){
		XplstdatO xplstdatO = bisDataDao.deleteDataCateProc(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO querybycate(){
		XplstdatO xplstdatO = bisDataDao.querybycate(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO queryByExt(){
		XplstdatO  xplstdatO = bisDataDao.queryByExt(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO queryByExt5(){
		XplstdatO xplstdatO = bisDataDao.queryByExt5(xplstdatI);
		return xplstdatO;
	}
	public XplstdatO errActionFnc(){
		XplstdatO  xplstdatO = new XplstdatO();
		xplstdatO.setTrx_id("XPLSTDAT");
		xplstdatO.setType_id("O");
		xplstdatO.setRtn_code("0000009");
		xplstdatO.setRtn_mesg("Invalid Action_flg");
		return xplstdatO;
	}
	private XplstdatO deleteByDataCateExt1() {
		XplstdatIA iary = xplstdatI.getIary().get(0);
		String data_cate,data_ext,ext_1;
		data_cate = iary.getData_cate();
		data_ext = iary.getData_ext();
		ext_1 = iary.getExt_1();
		String hql = "FROM Bis_data WHERE DATA_CATE=? AND DATA_EXT=? AND EXT_1=?";
		Bis_data bis_data = bisDataDao.uniqueResult(hql, data_cate,data_ext,ext_1);
		if(bis_data == null){
		}else{
			bisDataDao.delete(bis_data);
		}
		xplstdatO.setRtn_code(RETURN_CODE_OK);
		xplstdatO.setRtn_mesg(RETURN_MESG_OK);
		return xplstdatO;
	}
	private XplstdatO addByDataCateExt1() {
		int i=0;
		String data_cate,data_ext,ext_1,ext_2,data_desc;
		for(i=0;i<xplstdatI.getTbl_cnt();i++){
			XplstdatIA iary = xplstdatI.getIary().get(i);
			data_cate = iary.getData_cate();
			data_ext = iary.getData_ext();
			ext_1 = iary.getExt_1();
			ext_2 = iary.getExt_2();
			data_desc = iary.getData_desc();
			String sql = "FROM Bis_data WHERE DATA_CATE=? AND DATA_EXT=? AND EXT_1=?";
			List<Bis_data> bis_data_list = bisDataDao.listWithLock(sql, data_cate,data_ext,ext_1);
			if(bis_data_list.size() >1){
				xplstdatO.setRtn_code(RETURN_CODE_SET_ERROR);
				xplstdatO.setRtn_mesg("此记录不止一条，请检查！");
				return xplstdatO;
			}
			/**
			 * 是否存储厂别在UROP(人员与站点的关系)
			 */
			if(bis_data_list.size()==0){
				Bis_data bis_data = new Bis_data();
				bis_data.setData_seq_id(GUIDGenerator.javaGUID());
				bis_data.setUnq_seq_id(GUIDGenerator.javaGUID());
				bis_data.setData_cate(data_cate);
				bis_data.setData_ext(data_ext);
				bis_data.setData_desc(data_desc);
				bis_data.setExt_1(ext_1);
				bis_data.setExt_2(ext_2);
				bisDataDao.save(bis_data);
			}else if(bis_data_list.size()==1){
				Bis_data bis_data = bis_data_list.get(0);
				bis_data.setExt_2(ext_2);
				bis_data.setData_desc(data_desc);
				bisDataDao.update(bis_data);
			}
		}
		xplstdatO.setRtn_code(RETURN_CODE_OK);
		xplstdatO.setRtn_mesg(RETURN_MESG_OK);
		return xplstdatO;
	}
	private XplstdatO queryDataByCateUser() {
		String data_cate="",data_ext="",user_id="";
		int i=0;
		List<XplstdatOA> oaryList =new ArrayList<XplstdatOA>();
		List<Bis_data> bisDataList = new ArrayList<Bis_data>();
		XplstdatIA iary = xplstdatI.getIary().get(0);
		data_cate = iary.getData_cate();
		data_ext = iary.getData_ext();
		user_id = iary.getUser_id();
		String admin_sql = "FROM Bis_data where data_cate='UFUG'AND DATA_EXT='"+user_id+
				"' AND EXT_1='ADMIN'AND EXT_3='Y'";
		List<Bis_data> UFUG_list = bisDataDao.find(admin_sql);
		if(UFUG_list.size()==1){
			String hql = "FROM Bis_data where data_cate ='"+data_cate+ "'";
			if (iary.getData_ext() != null) {
				hql = hql + " AND data_ext in(" + iary.getData_ext() + ") ORDER BY CONVERT(DATA_ITEM,UNSIGNED)";
			}
			bisDataList = bisDataDao.find(hql);
		}else{
			String sql="SELECT * FROM BIS_DATA A  JOIN BIS_DATA B ON A.DATA_ID = B.EXT_1 WHERE  " +
					"A.DATA_CATE ='"+data_cate+"' AND A.DATA_EXT IN("+data_ext+")"+
					"AND B.DATA_CATE IN('URDT')AND B.DATA_EXT='"+user_id+"' ORDER BY CONVERT(B.DATA_ITEM,UNSIGNED)";
			bisDataList = bisDataDao.findBySQL(sql, Bis_data.class);
		}
		for (Bis_data bis_data : bisDataList) {
			XplstdatOA oary = new XplstdatOA();
			oary.setData_cate(bis_data.getData_cate());
			oary.setData_desc(bis_data.getData_desc());
			oary.setData_ext(bis_data.getData_ext());
			oary.setData_id(bis_data.getData_id());
			oary.setData_item(bis_data.getData_item());
			oary.setExt_1(bis_data.getExt_1());
			oary.setExt_2(bis_data.getExt_2());
			oary.setExt_3(bis_data.getExt_3());
			oary.setExt_4(bis_data.getExt_4());
			oary.setExt_5(bis_data.getExt_5());
			oaryList.add(oary);
		}
		xplstdatO.setRtn_code(RETURN_CODE_OK);
		xplstdatO.setRtn_mesg(RETURN_MESG_OK);
		xplstdatO.setOary(oaryList);
		xplstdatO.setTbl_cnt(oaryList.size());
		return xplstdatO;
	}
	
	private XplstdatO queryDataByFabUser() {
		String data_cate="",data_ext="",user_id="";
		List<XplstdatOA> oaryList =new ArrayList<XplstdatOA>();
		List<Bis_data> bisDataList = new ArrayList<Bis_data>();
		XplstdatIA iary = xplstdatI.getIary().get(0);
		data_cate = iary.getData_cate();
		data_ext = iary.getData_ext();
		user_id = iary.getUser_id();
		String admin_sql = "FROM Bis_data where data_cate='UFUG'AND DATA_EXT='"+user_id+
				"' AND EXT_1='ADMIN'AND EXT_3='Y'";
		List<Bis_data> UFUG_list = bisDataDao.find(admin_sql);
		if(UFUG_list.size()==1){
			String hql = "FROM Bis_data where data_cate ='"+data_cate+ "'";
			if (iary.getData_ext() != null) {
				hql = hql + " AND data_ext in(" + iary.getData_ext() + ") ORDER BY CONVERT(DATA_ITEM,UNSIGNED)";
			}
			bisDataList = bisDataDao.find(hql);
		}else{
			String sql=" SELECT * FROM BIS_DATA A  JOIN BIS_DATA B ON A.DATA_ID = B.EXT_1 WHERE " ;
				sql += " A.DATA_CATE = '" + data_cate + "' AND A.DATA_EXT IN ( "+data_ext+" ) " +
					" AND B.DATA_CATE IN('URDT')AND B.DATA_EXT='"+user_id+"' ORDER BY CONVERT(B.DATA_ITEM,UNSIGNED)";
			bisDataList = bisDataDao.findBySQL( sql , Bis_data.class );
		}
		for (Bis_data bis_data : bisDataList) {
			XplstdatOA oary = new XplstdatOA();
			oary.setData_cate(bis_data.getData_cate());
			oary.setData_desc(bis_data.getData_desc());
			oary.setData_ext(bis_data.getData_ext());
			oary.setData_id(bis_data.getData_id());
			oary.setData_item(bis_data.getData_item());
			oary.setExt_1(bis_data.getExt_1());
			oary.setExt_2(bis_data.getExt_2());
			oary.setExt_3(bis_data.getExt_3());
			oary.setExt_4(bis_data.getExt_4());
			oary.setExt_5(bis_data.getExt_5());
			oaryList.add(oary);
		}
		xplstdatO.setRtn_code(RETURN_CODE_OK);
		xplstdatO.setRtn_mesg(RETURN_MESG_OK);
		xplstdatO.setOary(oaryList);
		xplstdatO.setTbl_cnt(oaryList.size());
		return xplstdatO;
	}
	private XplstdatO listDataBySort() {
		String data_cate,data_ext;
		List<XplstdatOA> oaryList =new ArrayList<XplstdatOA>();
		List<Bis_data> bisDataList = new ArrayList<Bis_data>();
		XplstdatIA iary = xplstdatI.getIary().get(0);
		data_cate = iary.getData_cate();
		data_ext = iary.getData_ext();
		String sql = "FROM Bis_data where data_cate='"+data_cate+"'AND data_ext='"+data_ext+
						"'ORDER BY CONVERT(EXT_2,UNSIGNED)";
		bisDataList = bisDataDao.find(sql);
		for(Bis_data bis_data : bisDataList){
			XplstdatOA oary = new XplstdatOA();
			oary.setData_cate(bis_data.getData_cate());
			oary.setData_desc(bis_data.getData_desc());
			oary.setData_ext(bis_data.getData_ext());
			oary.setData_id(bis_data.getData_id());
			oary.setData_item(bis_data.getData_item());
			oary.setExt_1(bis_data.getExt_1());
			oary.setExt_2(bis_data.getExt_2());
			oary.setExt_3(bis_data.getExt_3());
			oary.setExt_4(bis_data.getExt_4());
			oary.setExt_5(bis_data.getExt_5());
			oaryList.add(oary);
		}
		xplstdatO.setRtn_code(RETURN_CODE_OK);
		xplstdatO.setRtn_mesg(RETURN_MESG_OK);
		xplstdatO.setOary(oaryList);
		xplstdatO.setTbl_cnt(oaryList.size());
		return xplstdatO;
	}
}
